package com.elite.groovy.callback

import com.elite.groovy.kh.KHUtil
import com.elite.groovy.util.EliteBean
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
* @Title:防伪查询结果推送
* @Description:防伪查询结果推送
* @Param:
* @return:
* @Author: TH
* @Date: 2023/10/27
*/
public class apiIVRSecurityPush implements ServiceBackInvoke {

    private static final Log log = LogFactory.getLog(apiIVRSecurityPush.class);

    @Override
    String doCallBack(EliteBean eliteBean, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        // 初始化返回参数
        JSONObject result = new JSONObject();

        // 获取接口调用方式及参数
        String getMethod = httpServletRequest.getMethod();
        log.debug("[getMethod]:" + getMethod);

        String inData = "";
        if (getMethod.equals("GET")) {
            inData = httpServletRequest.getParameter("data");
            log.debug("[原始Get请求参数]:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(httpServletRequest.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("[原始Post请求参数]:" + inData);
        }
        log.info("[调用请求信息]:" + inData);

        //  入参为空
        if (KHUtil.isNull(inData)) {
            log.debug("【防伪查询结果推送】入参为空-无法完成操作!");
            result.put("status", -2);
            result.put("msg", "入参为空-无法完成操作!");
            result.put("data", "{}");
            //写入接口日志表
            String logsql = "insert into dg_api_log(rec_guid,api_type,request_body,back_body,request_time,remarks)values(uuid(),?,?,?,now(),?)";
            jt.update(logsql, "apiSecurityPush", inData.toString(), result.toString(), "防伪查询结果推送接口");
            return result.toString();
        }


        try {

            //解析请求的jSON
            JSONObject inJson = JSONObject.fromObject(inData);
            String pretplcode = inJson.getString("pretplcode");
            String segment = inJson.getString("segment");
            String posttplcode = inJson.getString("posttplcode");
            String tag = inJson.getString("tag");
            String phone = inJson.getString("phone");//手机号
            String callId = inJson.getString("callId");//电话唯一值
            String querytime = inJson.getString("querytime");//查询时间
            String securitycode = inJson.getString("securitycode");//防伪码
            String queryresult = inJson.getString("queryresult");//防伪查询结果
            String querychannel = inJson.getString("querychannel");//防伪查询渠道
            String querytotal = inJson.getString("querytotal");//防伪码查询总次数
            if (KHUtil.isNull(pretplcode) ||
                    KHUtil.isNull(segment) ||
                    KHUtil.isNull(posttplcode) ||
                    KHUtil.isNull(phone) ||
                    KHUtil.isNull(callId) ||
                    KHUtil.isNull(querytime) ||
                    KHUtil.isNull(securitycode) ||
                    KHUtil.isNull(queryresult)||
                    KHUtil.isNull(querychannel) ||
                    KHUtil.isNull(querytotal)
            ) {
                log.debug("【防伪查询结果推送】参数值为空-无法完成操作!");
                result.put("status", -2);
                result.put("msg", "参数值为空-无法完成操作!");
                result.put("data", "{}");
                //写入接口日志表
                String logsql = "insert into dg_api_log(rec_guid,api_type,request_body,back_body,request_time,remarks)values(uuid(),?,?,?,now(),?)";
                jt.update(logsql, "apiSecurityPush", inData.toString(), result.toString(), "防伪查询结果推送接口");
                return result.toString();
            }

            //判断是否是约定好的固定值
            if (!pretplcode.equals("Local_Interface_input")  || !segment.equals("formcond") || !posttplcode.equals("Interface_out_detail")|| !tag.equals("tianrun")) {
                log.debug("【防伪查询结果推送】固定值不正确-无法完成操作!");
                result.put("status", -2);
                result.put("msg", "固定值不正确-无法完成操作!");
                result.put("data", "{}");
                //写入接口日志表
                String logsql = "insert into dg_api_log(rec_guid,api_type,request_body,back_body,request_time,remarks)values(uuid(),?,?,?,now(),?)";
                jt.update(logsql, "apiSecurityPush", inData.toString(), result.toString(), "防伪查询结果推送接口");
                return result.toString();
            }


            //开始查找id是否在表里存在，存在则UPDATE 不存在insert
            String selectsql = "select callId   from dg_security_list where callId=?  ";

            List<Map<String, Object>> selelctList = jt.queryForList(selectsql, callId);
           //存在修改---写入历史表
           if (selelctList.size()>0){
               String inserhissql='''
                           insert into dg_security_list_his(rec_his_guid,rec_guid,callId,phone,querytime,securitycode,queryresult,createddate,createddate_his,querychannel,querytotal)
                           select uuid(),rec_guid,callId,phone,querytime,securitycode,queryresult,createddate,now(),querychannel,querytotal from dg_security_list where callId=?
                                 ''';
               jt.update(inserhissql,callId);
               String UpdateSql='''
                             update dg_security_list
                             Set 
                             phone=?,
                             querytime=?,
                             securitycode=?,
                             queryresult=?,
                             querychannel=?,
                             querytotal=?,
                             updateDate=now()
                              where callId=?
                                  ''';
                 jt.update(UpdateSql,phone,querytime,securitycode,queryresult,querychannel,querytotal,callId);

           }else{

               String insertsql='''
                             insert into dg_security_list
                             ( 
                             rec_guid,
                             callId,
                             phone,
                             querytime,
                             securitycode,
                             queryresult,
                             createddate,querychannel,querytotal
                                )values(uuid(),?,?,?,?,?,now(),?,?)
                                  ''';
               jt.update(insertsql,callId,phone,querytime,securitycode,queryresult,querychannel,querytotal);
           }


                result.put("pretplcode",pretplcode);
                result.put("posttplcode",posttplcode);
                result.put( "segment",segment);
                result.put("tag",tag);
                result.put("callId",callId);
                result.put("querytime",querytime);
                result.put("querychannel",querychannel);
                result.put("querytotal",querytotal);
                result.put("phone",phone);
                result.put("queryresult",queryresult);
                result.put("securitycode",securitycode);


            log.debug("【防伪查询结果推送】成功返回的JSON报文："+result);
            //写入接口日志表
            String logsql="insert into dg_api_log(rec_guid,api_type,request_body,back_body,request_time,remarks)values(uuid(),?,?,?,now(),?)";
            jt.update(logsql, "apiSecurityPush",inData.toString(),result.toString(),"防伪查询结果推送接口");







        } catch (Exception e) {
            log.error("【防伪查询结果推送】数据处理错误:", e);
            result.put("status", -1);
            result.put("msg", "数据处理错误[" + e.getMessage() + "]");
            result.put("data", "{}");
            //写入接口日志表
            String logsql = "insert into dg_api_log(rec_guid,api_type,request_body,back_body,request_time,remarks)values(uuid(),?,?,?,now(),?)";
            jt.update(logsql, "apiSecurityPush", inData.toString(), result.toString(), "防伪查询结果推送接口");
        }


        return result
    }
}
